package com.personal.core.delay;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 有生产日期和保质期的
 * @author cuibo
 *
 */
public abstract class CreateAndExpiry implements Delayed
{

    /** 生产日期 */
    private long createDate;
    
    /** 保质期限 */
    private long expirydate;
    
    public CreateAndExpiry()
    {
        super();
    }

    public CreateAndExpiry(long createDate, long expirydate)
    {
        super();
        this.createDate = createDate;
        this.expirydate = expirydate;
    }
    
    /**
     * 获取秒级别的延迟时间
     * @return
     */
    public long getSecondsDelay()
    {
        return getDelay(TimeUnit.SECONDS);
    }

    @Override
    public int compareTo(Delayed other)
    {
        if (other == this) // compare zero ONLY if same object
            return 0;
        if (other instanceof CreateAndExpiry)
        {
            CreateAndExpiry x = (CreateAndExpiry) other;
            long d = expirydate + createDate - (x.expirydate + x.createDate);
            return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
        }
        long d = (getDelay(TimeUnit.NANOSECONDS) - other.getDelay(TimeUnit.NANOSECONDS));
        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
    }

    @Override
    public long getDelay(TimeUnit unit)
    {
        return unit.convert(expirydate - (System.currentTimeMillis() - createDate), TimeUnit.MILLISECONDS);
    }

    public long getCreateDate()
    {
        return createDate;
    }

    public void setCreateDate(long createDate)
    {
        this.createDate = createDate;
    }

    public long getExpirydate()
    {
        return expirydate;
    }

    public void setExpirydate(long expirydate)
    {
        this.expirydate = expirydate;
    }

}
